package com.yibing.plat;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class Acceptor implements Runnable {
	
	public Acceptor(int p) {
		this(p, null, null);
	}
	
	public Acceptor(int p, Receiver r, Sender s) {
		port = p;
		receiver = r;
		sender = s;		
	}

	@Override
	public void run() {
		try {
			ServerSocket server = new ServerSocket(port);
			while (true) {
				Socket client = server.accept();
				Logger.log("Accept a conn from " + client.getInetAddress().getHostAddress() 
						+ ":" + client.getPort());
				if (receiver != null) {
					Logger.log("Start a receiver for "+ client.getInetAddress().getHostAddress() 
						+ ":" + client.getPort());
					receiver.setClientSocket(client);
					receiver.start();
				}
				if (sender != null) {
					Logger.log("Start a sender for "+ client.getInetAddress().getHostAddress() 
						+ ":" + client.getPort());
					sender.setOutputStream(client.getOutputStream());
					sender.start();
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void start() {
		new Thread(this).start();
	}

	private int port;

	private Receiver receiver;
	
	private Sender sender;
	
}
